package cn.xorange.commons.security.interceptor;


import cn.xorange.commons.security.annotation.PassToken;
import cn.xorange.commons.security.exception.SecurityException;
import cn.xorange.commons.security.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Objects;

@Slf4j
public class ResponseInterceptor implements HandlerInterceptor {

    @Resource
    InterceptRepeatSubmit interceptRepeatSubmit;
    @Resource
    PermissionService permissionService;

    /**
     * 预处理回调方法，实现处理器的预处理（如检查登陆），第三个参数为响应的处理器，自定义Controller
     * 返回值：true表示继续流程（如调用下一个拦截器或处理器）；false表示流程中断（如登录检查失败），不会继续调用其他的拦截器或处理器，此时我们需要通过response来产生响应；
     *
     * SpringSecurity放行页面，  JwtAuthTokenFilter 放行之后进入该方法进行2次验证拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof ResourceHttpRequestHandler){
            return true;
        }else if(handler instanceof BasicErrorController){
            return true;
        }else {
            HandlerMethod handlerClazz=(HandlerMethod)handler;
            Method method = handlerClazz.getMethod();
            if(handlerClazz.getBean() instanceof BasicErrorController){
                Enumeration<String> attributeNames = request.getAttributeNames();
                StringBuilder sb = new StringBuilder();

                Object msg1 = request.getAttribute("org.springframework.boot.web.servlet.error.DefaultErrorAttributes.ERROR");


                if(Objects.nonNull(msg1)){
                    sb.append(msg1);
                }else {
                    Object msg2 = request.getAttribute("javax.servlet.error.exception");
                    sb.append(msg2);
                }


                //Set<Object> set = new HashSet<>();
                //Set<String> names =new HashSet<>();
                //while (attributeNames.hasMoreElements()){
                //    String name = attributeNames.nextElement();
                //    if(name.contains("error")){
                //        names.add(name);
                //        set.add(request.getAttribute(name));
                //        sb.append(request.getAttribute(name));
                //        sb.append("  ");
                //    }
                //}

                String msg = sb.toString();
                log.debug(msg);
                throw SecurityException.systemError(msg);
            } else {
                // 检查恶意攻击
                this.interceptRepeatSubmit.checkRateLimiter(method);

                //检查是否有passToken注释，有则跳过认证
                if (method.isAnnotationPresent(PassToken.class)) {
                    PassToken passToken = method.getAnnotation(PassToken.class);
                    if (Boolean.TRUE.equals(passToken.pass())) {
                        return true;
                    }
                }

                // 判断权限
                return this.permissionService.verifyAuth(response,handlerClazz,method);
            }
        }
    }





    /**
     * 后处理回调方法，实现处理器的后处理（但在渲染视图之前），此时我们可以通过modelAndView（模型和视图对象）对模型数据进行处理或对视图进行处理，modelAndView也可能为null。
     */
    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        // 后处理回调方法
    }

    /**
     * 整个请求处理完毕回调方法，即在视图渲染完毕时回调，如性能监控中我们可以在此记录结束时间并输出消耗时间，还可以进行一些资源清理，类似于try-catch-finally中的finally，但仅调用处理器执行链中
     */
   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
       // 整个请求处理完毕回调方法
    }


}
